package com.thread.thread.RateLimiter_令牌桶;

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.TimeUnit;

public class RateLimiterTest {


	public static void main(String[] args) throws  Exception{
		//代表每秒生产令牌的数量，也叫每秒许可数或者qps
		final RateLimiter rateLimiter = RateLimiter.create(2.0);

		Thread[] threads=new Thread[10];

		for(int i=0;i<threads.length;i++){

			threads[i]= new Thread() {
				@Override
				public void run() {
					//已阻塞方式获取令牌，此列说明：每次需要一个消费一个令牌，令牌的产生数量约每秒两个，所以每个线程之间的间隔接近0.5s的时间
//					double time=rateLimiter.acquire(1);
//					System.out.println(time);
					//从RateLimiter 获取令牌，正常比create多1 如下：获取一个令牌，最多等待十秒，无参数时代表立即获取
					if(rateLimiter.tryAcquire(1, 1, TimeUnit.SECONDS)){
						System.out.println("获得许可"+","+Thread.currentThread().getName());
					}else{
						System.out.println("为获得许可"+","+Thread.currentThread().getName());
					}

				}
			};
			threads[i].setName("线程"+i);
		}

		for(int i=0;i<threads.length;i++){
			threads[i].start();
		}

		for(int i=0;i<threads.length;i++){
			threads[i].join();
		}

	}

}
